import React from 'react'
import type { NavigateOptions } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'

/**
 * window.location.href= '/' 跳转需带上参数，改用
 * window.location.href = getUrlWithParams('/')
 *
 */

export function getUrlWithParams(to: string): string {
  const params = new URL(window.location.href).searchParams
  // 像素ID
  const fbPixelId = params.get('fbPixelId')
  const tkPixelId = params.get('tkPixelId')
  // 老带新
  const reCode = params.get('reCode')
  // 转盘参数
  const turntableCode = params.get('turntableCode')
  // 代理参数
  const code = params.get('code')
  const linkId = params.get('linkId')
  // w2a
  const org = params.get('org')

  const url = new URL(to, window.location.origin)

  if (fbPixelId) {
    url.searchParams.set('fbPixelId', fbPixelId)
  }
  if (tkPixelId) {
    url.searchParams.set('tkPixelId', tkPixelId)
  }
  if (reCode) {
    url.searchParams.set('reCode', reCode)
  }
  if (turntableCode) {
    url.searchParams.set('turntableCode', turntableCode)
  }
  if (linkId) {
    url.searchParams.set('linkId', linkId)
  }
  if (code) {
    url.searchParams.set('code', code)
  }
  if (org) {
    url.searchParams.set('org', org)
  }
  // console.log('fbPixelId', fbPixelId)
  // console.log('url', url)
  return url.pathname + url.search
}

export function useNavigateWithParams() {
  const navigate = useNavigate()

  function handleNavigate(to: string | number, options?: NavigateOptions) {
    if (typeof to === 'number') {
      return navigate(to)
    }
    const newTo = getUrlWithParams(to)
    navigate(newTo, options)
  }

  return handleNavigate
}

export type RouterType = { navigate: ReturnType<typeof useNavigate> } & ReturnType<
  typeof useLocation
>

export const WithRouter = <Props extends RouterType>(Component: React.FC<Props>) => {
  const EnhancedComponent: React.FC<Props> = (props) => {
    const navigate = useNavigateWithParams()
    const location = useLocation()

    return <Component {...props} navigate={navigate} {...location} />
  }

  return EnhancedComponent
}
